package org.finesys.quartz.support;

import lombok.extern.slf4j.Slf4j;
import org.finesys.common.core.util.SpringContextHolder;
import org.finesys.common.quartz.core.exception.TaskException;
import org.finesys.quartz.entity.SysJob;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * springBean 调用实现
 */
@Component
@Slf4j
public class TaskInvokeSpringBeanServiceImpl implements TaskInvokeService {

    @Override
    public void invoke(SysJob sysJob) throws TaskException {
        try {
            // 通过Spring上下文去找 也有可能找不到
            Object object = SpringContextHolder.getBean(sysJob.getClassName());
            Method method;
            if (StringUtils.hasText(sysJob.getMethodParamsValue())) {
                String[] params = sysJob.getMethodParamsValue().split(",");
                Class<?>[] parameterTypes = new Class[params.length];
                for (int i = 0; i < params.length; i++) {
                    parameterTypes[i] = String.class;
                }
                method = object.getClass().getDeclaredMethod(sysJob.getMethodName(), parameterTypes);
                ReflectionUtils.makeAccessible(method);
                method.invoke(object, (Object[]) params);
            } else {
                method = object.getClass().getDeclaredMethod(sysJob.getMethodName());
                ReflectionUtils.makeAccessible(method);
                method.invoke(object);
            }
        } catch (NoSuchMethodException e) {
            log.error("定时任务spring bean反射异常方法未找到,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务spring bean反射异常方法未找到,执行任务：" + sysJob.getClassName());
        } catch (InvocationTargetException e) {
            log.error("定时任务spring bean反射执行异常,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务spring bean反射执行异常,执行任务：" + sysJob.getClassName());
        } catch (IllegalAccessException e) {
            log.error("定时任务spring bean反射异常,执行任务：{}", sysJob.getClassName());
            throw new TaskException("定时任务spring bean反射异常,执行任务：" + sysJob.getClassName());
        }
    }
}
